package com.stylefeng.guns.modular.fileManage.controller;

import com.stylefeng.guns.common.persistence.dao.ZyBrewsPictureMapper;
import com.stylefeng.guns.common.persistence.dao.ZyTeaMapper;
import com.stylefeng.guns.common.persistence.model.ZyBrewsPicture;
import com.stylefeng.guns.common.persistence.model.ZyPicture;
import com.stylefeng.guns.modular.fileManage.dao.*;
import com.stylefeng.guns.modular.fileManage.enums.TeaLabelEnums;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.ZyBrewsMapper;
import com.stylefeng.guns.common.persistence.model.ZyBrews;
import com.stylefeng.guns.common.persistence.model.ZyRecycle;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.page.PageBT;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.PagingHandler;
import com.stylefeng.guns.modular.fileManage.service.impl.ZyPictureServiceImpl;
import com.stylefeng.guns.modular.fileManage.warpper.PictureWarpper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 冲泡方式控制器
 *
 * @author fengshuonan
 * @Date 2017-12-25 15:28:28
 */
@Controller
@RequestMapping("/brews")
public class BrewsController extends BaseController {

    private String PREFIX = "/fileManage/brews/";

    @Autowired
    private ZyPictureServiceImpl pictureService;

    @Autowired
    private ZyBrewsMapper brewsService;

    @Autowired
    private ZyRecycleDao zyRecycle;

    @Autowired
    private ZyTeaDao teaDao;

    @Autowired
    private ZyBrewsDao zyBrewsDao;

    @Autowired
    private ZyTeaMapper teaMapper;

    @Autowired
    private ZyBrewsPictureDao zyBrewsPictureDao;

    @Autowired
    private ZyPictureDao pictureDao;

    @Autowired
    private ZyBrewsPictureDao brewsPictureDao;

    /**
     * 跳转到冲泡方式首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "brews.html";
    }

    /**
     * 跳转到添加冲泡方式
     */
    @RequestMapping("/brews_add")
    public String brewsAdd() {
        return PREFIX + "brews_add.html";
    }

    /**
     * 跳转到修改冲泡方式
     */
    @RequestMapping("/brews_update/{brewsId}")
    public String brewsUpdate(@PathVariable Integer brewsId, Model model) {
        ZyBrews brews = brewsService.selectById(brewsId);
        model.addAttribute("brews", brews);
        LogObjectHolder.me().set(brews);
        //查找冲泡方式对应的图片
        List<ZyBrewsPicture> brewsPictures = zyBrewsPictureDao.selectByBrewsId(brews.getId());
        for(int i=0;i<brewsPictures.size();i++){
            Integer pictureId = brewsPictures.get(i).getPictureId();
            ZyPicture picture = pictureDao.selectByPictureId(pictureId);
            PictureWarpper picWar = new PictureWarpper(picture);
            Map<String,Object> pictureMap = (Map<String,Object>)super.warpObject(picWar);
            model.addAttribute("pictureMap" + (brewsPictures.get(i).getSequence() + 1), pictureMap);
        }
        return PREFIX + "brews_edit.html";
    }

    /**
     * 跳转到图片选择框
     */
    @RequestMapping("/brews_picture")
    public String brewsPicture(Model model, PageBT pageParam, @RequestParam("brewsId") Integer brewsId, @RequestParam("sequence") Integer sequence) {
        List<ZyPicture> resultPictures = new ArrayList<>();
        List<Integer> picIds = new ArrayList<>();
        //查询出图片(offset和limit置为空则查询表的所有记录)
        PageInfoBT pageInfo;
        if (brewsId == null) {
            //新增界面
            pageInfo = PagingHandler.getPageResult("zy_picture", pageParam);
            resultPictures = pageInfo.getRows();
            model.addAttribute("openType", "brewsAdd");
        } else {
            //编辑页面
            pageInfo = PagingHandler.getPageResultByBrews(pageParam,brewsId,sequence);
            List<ZyBrewsPicture> originalZbps = brewsPictureDao.selectByBrewsIdAndSequence(brewsId,sequence);
            //将选中的图片id包装isChecked=true
            for(int i = 0;i<originalZbps.size();i++){
                picIds.add(originalZbps.get(i).getPictureId());
            }

            resultPictures = pageInfo.getRows();
            ZyBrews brewsItem = brewsService.selectById(brewsId);
            if(brewsItem == null){
                brewsItem = new ZyBrews();
                brewsItem.setName("新增冲泡方式");
            }
            model.addAttribute("brewsItem", brewsItem);
            model.addAttribute("openType", "brewsEdit");
        }
        PictureWarpper picWar = new PictureWarpper(resultPictures, picIds);
        pageInfo.setRows((List) super.warpObject(picWar));
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("sequence", sequence);
        return "/fileManage/picture/picture_Selector.html";
    }

    /**
     * 关联冲泡方式和图片
     */
    @RequestMapping("/selector")
    @ResponseBody
    public Object selector(@RequestParam("brewsId") Integer brewsId, @RequestParam("sequence") Integer sequence, @RequestParam("ids") String ids) {
        //图片的id数组
        String[] pictureIdStr = ids.split("-");
        Integer[] pictureIds = new Integer[pictureIdStr.length];
        for (int i = 0; i < pictureIdStr.length; i++) {
            pictureIds[i] = Integer.parseInt(pictureIdStr[i]);
        }
        //遍历图片id集合
        for (int i = 0; i < pictureIds.length; i++) {
            pictureService.selectorPictureByBrews(brewsId, sequence,pictureIds[i]);
        }
        return SUCCESS_TIP;
    }

    /**
     * 获取冲泡方式列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return zyBrewsDao.list(condition);
    }

    /**
     * 查看冲泡方式更多详情
     *
     * @return
     */
    @RequestMapping("/showMoreDetail")
    public String showMoreDetail(@RequestParam("id")Integer teaId, Model model) {
        ZyBrews brews = brewsService.selectById(teaMapper.selectById(teaId).getBrewsId());
        model.addAttribute("brewsItem",brews);
        return "/fileManage/teaFile/frontView/goBack.html";
    }

    /**
     * 新增冲泡方式
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ZyBrews brews) {
        //查出上一条记录的ID 加一变成下一条的ID
        int maxId = zyBrewsDao.selectMaxId();
        int id = maxId + 1;
        //查询冲泡方式的名称是否已经存在
        List<ZyBrews> brewsList = zyBrewsDao.selectByName(brews.getName());
        if (brewsList != null && brewsList.size() > 0) {
            throw new BussinessException(BizExceptionEnum.BREWS_NAME_IS_EXIST);
        }

        brews.setId(id);
        brews.setStatus(1);
        brews.setCrtUser(ShiroKit.getUser().getAccount());
        brews.setCrtTime(new Date());
        zyBrewsDao.insert(brews);
        return brews;
    }

    /**
     * 删除冲泡方式
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(required = false) Integer brewsId, @RequestParam(required = false) String brewsName) {
        ZyBrews zyBrews = new ZyBrews();
        zyBrews.setId(brewsId);
        zyBrews.setStatus(3);
        brewsService.updateById(zyBrews);
        //放入回收站
        ZyRecycle item = new ZyRecycle();
        item.setId(brewsId);
        item.setKeyName("name");
        item.setKeyValue(brewsName);
        item.setTableName("zy_brews");
        item.setCrtUser(ShiroKit.getUser().getAccount());
        item.setCrtTime(new Date());
        zyRecycle.addRecycle(item);
        //将茶叶中关联的brews置为空
        teaDao.updateBrewsIdToNull(brewsId);
        return SUCCESS_TIP;
    }

    /**
     * 修改冲泡方式
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ZyBrews brews) {
        brewsService.updateById(brews);
        ZyBrews newBrews = brewsService.selectById(brews.getId());
        return newBrews;
    }

    /**
     * 冲泡方式详情
     */
    @RequestMapping(value = "/detail/{brewsId}")
    @ResponseBody
    public Object detail(@PathVariable("brewsId") Integer brewsId) {
        return brewsService.selectById(brewsId);
    }
}
